<template>
  <div class="app-container">
    <div class="build-container">
      <el-steps :active="active" finish-status="success">
        <el-step title="步骤 1" description="构建reader">1</el-step>
        <el-step title="步骤 2" description="构建writer">2</el-step>
        <el-step title="步骤 3" description="字段映射">3</el-step>
        <el-step title="步骤 4" description="构建">4</el-step>
      </el-steps>

      <div v-show="active===1" class="step1">
        <Reader ref="reader" />
      </div>
      <div v-show="active===2" class="step2">
        <Writer ref="writer" />
      </div>
      <div v-show="active===3" class="step3">
        <Mapper ref="mapper" />
      </div>
      <div v-show="active===4" class="step4">
        <json-editor v-show="active===4" ref="jsonEditor" v-model="configJson" />
      </div>

      <el-button :disabled="active===1" style="margin-top: 12px;" @click="last">上一步</el-button>
      <el-button type="primary" style="margin-top: 12px;margin-bottom: 12px;" @click="next">
        {{ active!==4 ? '下一步' : '创建任务' }}
      </el-button>
      <el-button type="info" @click="handleCopy(inputData,$event)" v-show="active===4">复制json</el-button>
    </div>
  </div>
</template>

<script>
  import { buildJobJson } from '@data/api/data/datacollection'
  import { insert as jobInsert } from '@job/api/job/info'
  import { insertJobJson } from '@job/api/job/jobjson'

  // import Pagination from '@/components/Pagination'
  import { JsonEditor } from '@/components/JsonEditor'
  import Reader from './reader.vue'
  import Writer from './writer.vue'
  // import clip from '@/utils/clipboard'
  import Mapper from './mapper.vue'
  import { useDataStore } from '@/store/modules/data'
  // import Bus from './busReader'
  export default {
    name: 'DataCollection',
    components: {Reader, Writer, JsonEditor, Mapper},
    // inject: ['reload'],
    data() {
      return {
        configJson: '',
        active: 1,
        templateName: '',
        jobTemplateSelectDrawer: false,
        list: null,
        currentRow: null,
        listLoading: true,
        total: 0,
        listQuery: {
          current: 1,
          size: 10,
          jobGroup: 0,
          triggerStatus: -1,
          jobDesc: '',
          executorHandler: '',
          userId: 0
        },
        blockStrategies: [
          {value: 'SERIAL_EXECUTION', label: '单机串行'},
          {value: 'DISCARD_LATER', label: '丢弃后续调度'},
          {value: 'COVER_EARLY', label: '覆盖之前调度'}
        ],
        routeStrategies: [
          {value: 'FIRST', label: '第一个'},
          {value: 'LAST', label: '最后一个'},
          {value: 'ROUND', label: '轮询'},
          {value: 'RANDOM', label: '随机'},
          {value: 'CONSISTENT_HASH', label: '一致性HASH'},
          {value: 'LEAST_FREQUENTLY_USED', label: '最不经常使用'},
          {value: 'LEAST_RECENTLY_USED', label: '最近最久未使用'},
          {value: 'FAILOVER', label: '故障转移'},
          {value: 'BUSYOVER', label: '忙碌转移'}
          // { value: 'SHARDING_BROADCAST', label: '分片广播' }
        ],
        triggerNextTimes: '',
        registerNode: [],
        jobJson: '',
        temp: {
          // id: undefined,
          jobGroup: '1',
          jobCron: '0 0 3 * * ? *',
          jobDesc: '',
          author: 'admin',
          executorRouteStrategy: 'FIRST',
          executorBlockStrategy: 'SERIAL_EXECUTION',
          // childJobId: '',
          // executorFailRetryCount: '',
          // alarmEmail: '',
          // executorTimeout: '',
          // userId: 0,
          // jobConfigId: '',
          executorHandler: 'dataIntegrationJsonHandler',
          glueType: 'BEAN',
          // jobJson: '',
          executorParam: '',
          // replaceParam: '',
          // jvmParam: '',
          // incStartTime: ''
        }
      }
    },
    created() {
      // this.getJdbcDs()
      const dataStore = useDataStore()
      dataStore.setDataSourceId(undefined)
      // Bus.dataSourceId = undefined;
    },
    methods: {
      next() {
        // const readerJdbcUrl = this.$refs.reader.getData().jdbcUrl
        const fromColumnList = this.$refs.reader.getData().columns
        const toColumnsList = this.$refs.writer.getData().columns
        // const fromTableName = this.$refs.reader.getData().tableName
        // 第一步 reader 判断是否已选字段
        if (this.active === 1) {
          // 实现第一步骤读取的表和字段直接带到第二步骤
          // this.$refs.writer.sendTableNameAndColumns(fromTableName, fromColumnList)
          // 取子组件的数据
          // console.info(this.$refs.reader.getData())
          if(!this.getReaderData().datasourceId) {
            this.msgError("数据库源不能为空");
            return;
          }
          if(!this.getReaderData().tableName) {
            this.msgError("数据库表名不能为空");
            return;
          }
          //解析字段：按钮如果不点，不能执行下一步
          if(this.getReaderData().querySql.trim() != '' && this.getReaderData().parseState != 1) {
            this.msgError("请点击解析字段按钮");
            return;
          }
          this.active++
        } else {
          // 将第一步和第二步得到的字段名字发送到第三步
          if (this.active === 2) {
            if(!this.getWriterData().datasourceId) {
              this.msgError("数据库源不能为空");
              return;
            }
            if(!this.getWriterData().tableName) {
              this.msgError("数据库表名不能为空");
              return;
            }

            this.$refs.mapper.sendColumns(fromColumnList, toColumnsList)

            //设置全选
            // this.$refs.mapper.getLHandleCheckAllChange()
            // this.$refs.mapper.getRHandleCheckAllChange()
          }

          if (this.active === 3) {
              //获取 源端字段、目标字段
              let readerColumns = this.$refs.mapper.getLColumns().length
              let writerColumns = this.$refs.mapper.getRColumns().length

              if(readerColumns == 0) {
                this.msgError("源端字段不能为空");
                return;
              }
              if(writerColumns == 0) {
                this.msgError("目标字段不能为空");
                return;
              }

              if(readerColumns != writerColumns) {
                this.msgError("源端字段与目标字段数量不相同");
                return;
              }
              this.buildJson();
           }

          if (this.active === 4) {
            if(!this.configJson) {
              this.msgError("Datax脚本为空");
              return
            }

            // this.temp.jobJson = this.configJson
            this.temp.jobDesc = this.getWriterData().tableName + '【' + this.getReaderData().datasourceInfo  + '】'

            //先插入 json数据，再插入任务信息
            insertJobJson({'jsonContent': JSON.stringify(this.configJson), 'jsonJobName': this.temp.jobDesc}).then((res) => {
              this.temp.executorParam = '{"jsonJobId" : "' + res.data + '"}'
              jobInsert(this.temp).then(() => {
                this.$message({
                  message: '任务创建成功',
                  type: 'success',
                  duration: 2000,
                  onClose: () => {
                    // 重新加载，重置表单  todo 可以不需要刷新
                    location.reload()
                    
                    //重置表单
                    this.$refs.reader.resetForm()
                    this.$refs.writer.resetForm()
                    // 切回第一步
                    this.active = 1
                  }
                })
              })
            })
          } else {
            this.active++
          }
        }
      },
      last() {
        if (this.active > 1) {
          this.active--
        }
      },
      // 构建json
      buildJson() {
        const readerData = this.$refs.reader.getData()
        const writeData = this.$refs.writer.getData()
        const readerColumns = this.$refs.mapper.getLColumns()
        const writerColumns = this.$refs.mapper.getRColumns()

        //writerColumns 中，如果含有 斜线，需要转成 "/CUM/INDCU"  替换成  "`/CUM/INDCU`"
        // for(let i = 0; i < writerColumns.length; i++) {
        //   if(writerColumns[i].indexOf("/") > -1) {
        //     writerColumns.splice(i, 1, '`' + writerColumns[i] + '`')
        //   }
        // }
   
        const rdbmsReader = {
          readerSplitPk: readerData.splitPk,
          whereParams: readerData.where,
          querySql: readerData.querySql
        }
        const rdbmsWriter = {
          preSql: writeData.preSql,
          postSql: writeData.postSql
        }
        const obj = {
          readerDatasourceId: readerData.datasourceId,
          readerTables: [readerData.tableName],
          readerColumns: readerColumns,
          writerDatasourceId: writeData.datasourceId,
          writerTables: [writeData.tableName],
          writerColumns: writerColumns,
          rdbmsReader: rdbmsReader,
          rdbmsWriter: rdbmsWriter
        }
        // 调api
        buildJobJson(obj).then(response => {
          this.configJson = JSON.parse(response.data)
        })
      },
      async handleCopy(text, event) {
        await navigator.clipboard.writeText(text)
        // clip(this.configJson, event)
      },
      getReaderData() {
        if(this.$refs.reader){
          return this.$refs.reader.getData()
        }
      },
      getWriterData() {
        if(this.$refs.writer){
          return this.$refs.writer.getData()
        }
      },
      handleCurrentChange(val) {
        this.temp = Object.assign({}, val)
        this.temp.jobDesc = this.getWriterData().tableName + '【' + this.getReaderData().datasourceInfo  + '】'
        this.templateName = val.jobDesc
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
